const express = require('express')
const LoginService = require('../services/login-services')
const JSONResult =  require("../bean/json-result")


const router = express.Router()
const service = new LoginService()

/**
 * 登录页面
 */
router.get("/login.html",(req,res,next)=>{
    res.render("login",{title:"登录页面"})
    next()
})
/***
 * 登陆操作接口
 */
router.post('/login.do', async (req, res, next) => {
    const {path,params,query,body} = req
    const {username,password} = body
    // const RowDataPacket = await service.hasExist(username,password)
    const RowDataPacket = await service.getUser(username,password)
    console.log("HomeController====login==RowDataPacket:",RowDataPacket)
    const {id,nickname,avatar,email,role,age,sex,wechat,QQ,phone,address} = RowDataPacket[0]
    let json = {}
    if (id) {
        const user = {
            userId:id,
            username:username,
            password:password,
            nickname:nickname,
            avatar:avatar,
            email:email,
            role:role,
            age:age,
            sex:sex,
            phone:phone,
            wechat:wechat,
            QQ:QQ,
            address:address
        }
        //设置session
        req.session.user = user
        json = new JSONResult({code:200,message:"登陆成功！",data:{user:user}})
    } else {
        json = new JSONResult({code:404,message:"登陆失败，用户名密码错误！",data:{user:null}})
    }
    res.json(json)
    next()
})

/**
 * 退出操作
 */
router.get('/logout.do',(req, res, next) => {
    req.session.user = null
    //注销session
    //req.session.destroy()
    res.redirect("/login.html")
    next()
})

module.exports = router;
